<template>
	<div class="route-detail">
		<van-nav-bar fixed left-text="返回" left-arrow :title="!isWeixin() ? '采购单详情' : ''" @click-left="handleBack" />
		<!-- <van-overlay :show="overlayShow" @click="overlayShow = false" />
		<van-loading size="24px" color="#fff" text="加载中..." v-if="overlayShow" /> -->


		<div class="inner">
			<div class="name card">{{ detailInfo?.title || "-" }}</div>
			<div class="desc card">{{ detailInfo?.content || "-" }}</div>
			<div class="baojia card">
				<div class="title">报价进度</div>
				<div class="info">
					<div class="jdt">
						<van-progress :show-pivot="false" :percentage="jdFn(detailInfo?.buynum)" stroke-width="8" />
					</div>
					<div class="num">{{ detailInfo?.buynum || 0 }}/4</div>
				</div>
			</div>
			<div class="base card">
				<div class="title">基础信息</div>
				<div class="info">
					<div class="cloum">
						<div class="label">价格：</div>
						<div class="value">
							{{ detailInfo?.price || "***" }}
						</div>
					</div>
					<div class="cloum">
						<div class="label">联系人：</div>
						<div class="value">
							{{ detailInfo?.name || "***" }}
						</div>
					</div>
					<div class="cloum" @click="handlePhone">
						<div class="label">联系电话：</div>
						<div class="value">
							<span style="color: blue;" v-if="detailInfo?.buy===2">一键拨号</span>
							<span class="detailInfo?.buy===2?'blueSpan:''">{{ getPhone }}</span>
							<!-- <span>{{ getPhone }}</span> -->

						</div>
					</div>
				</div>
			</div>
			<div class="base card">
				<div class="title">其它信息</div>
				<div class="info">
					<div class="cloum">
						<div class="label">发布时间：</div>
						<div class="value">
							{{detailInfo?.addtime? dayjs.unix(detailInfo?.addtime).format("YYYY-MM-DD HH:mm:ss"): "-"}}
						</div>
					</div>
					<div class="cloum">
						<div class="label">收货地区：</div>
						<div class="value">
							{{
                detailInfo?.province + detailInfo?.city + detailInfo?.county ||
                "***"
              }}
						</div>
					</div>
					<div class="cloum">
						<div class="label">采购数量：</div>
						<div class="value">
							{{ detailInfo?.num || "***" }}
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- <div class="footer-cont" v-if="detailInfo?.buy === 1">
			<div class="btn-cloum">
				<van-button type="primary" color="#f60" block @click="handleSj">查看商机</van-button>
			</div>
			<div class="btn-cloum">
				<van-button type="primary" block @click="handleDz">独占商机</van-button>
			</div>
		</div> -->
		<!-- hdd  2024-6-6 修改判断，当前购买进度小于4的时候 就能一直购买 -->
		<div class="footer-cont" v-if="detailInfo?.buynum <4">
			<div class="btn-cloum">
				<van-button type="primary" color="#f60" block @click="handleSj">查看商机</van-button>
			</div>
			<div class="btn-cloum">
				<van-button type="primary" block @click="handleDz">独占商机</van-button>
			</div>
		</div>
		<!-- hdd 2024-6-19新增更多商机 -->
		<div class="moreBussiness">
			<div class="moreBussiness-title">
				<span>更多商机</span>
			</div>
			<div class="">
				<div class="moreBussiness-item" v-for="(item,index) in listAll" @click="goDetails(item)">
					<span>{{item.title}}</span>
					<span>{{item.content}}</span>
					<div>
						<van-progress :show-pivot="false" stroke-width="8"
							:percentage="item.buynum=='0'?'0':(item.buynum/4)*100" />
					</div>
					<div class="moreBussiness-item-foot">
						<span>{{item.province}}{{item.city}}{{dayjs.unix(detailInfo?.addtime).format("YYYY-MM-DD")}}</span>
						<span>剩余{{4-(item.buynum)}}次购买机会</span>
					</div>
				</div>
			</div>
		</div>
	</div>
	<BindPhone :show="bindPhoeShoe" @cancel="handlePhoneCancel" @confirm="handleBindPhoneConfirm"></BindPhone>
	<Recharge :procuresid="(id as string)" :show="rechargeShow" @cancel="handleCloseRecharge"></Recharge>
</template>
<script setup lang="ts">
	import { ref, computed, nextTick } from "vue";
	import * as dayjs from "dayjs";
	import { getCookie, isWeixin, setCookie } from "@/utils/index";
	import { useRouter, useRoute, LocationQueryValue } from "vue-router";
	import { Recharge, BindPhone } from "@/components";
	import { procureinfoApi, procurebuyApi, userphoneApi } from "@/api/detail";
	import { userInfoApi } from "@/api/user";
	// import { login } from "@/api/home";
	import wxchat from "@/utils/wechartSdk";
	import {
		showDialog,
		showLoadingToast,
		showConfirmDialog,
		showToast,
		showSuccessToast,
	} from "vant";
	const router = useRouter();
	const route = useRoute();
	const backUrl = router.options.history.state.back;
	let { id } = route.params;
	// const list = ref([]);
	const listAll = ref<any>({});
	// let pid : string | LocationQueryValue[];
	// pid = route.query.pid ? route.query.pid : '';

	const rechargeShow = ref(false);
	const bindPhoeShoe = ref(false);
	const detailInfo = ref<any>({});
	const getDetail = async () => {
		let { data, list } = await procureinfoApi({
			uid: getCookie("token") ? Number(getCookie("token")) : "",
			procuresid: Number(id),
		});
		console.log('data', data)
		if (!data.id) {
			showDialog({
				message: "采购单不存在",
				theme: "round-button",
			}).then(() => {
				// on close
				router.push("/user");
			});
		} else {
			detailInfo.value = data;
			listAll.value = list;
			wxchat.share({
				title: data?.title,
				desc: "我想让你看一下这个方案！！已经帮数千人降低线索成本了！！！",
				// link: window.location.href.split("#")[0] + '?pid=' + Number(getCookie("token")),
				link: window.location.href.split("#")[0],
				image: "http://zdb.suishilian.com/upload/yyb.jpg",
			});
		}
	};
	getDetail();


	let getPhone = computed(() => {
		let p = detailInfo?.value?.phone || "";
		console.log(p, 12233);
		if (p && detailInfo.value.buy === 1) {
			if (p.length <= 4) {
				p = p.slice(0, -2) + "**";
			} else {
				p = p.slice(0, -7) + "*******";
			}
		}
		return p || "******";
	});
	const params = new URLSearchParams(location.search);

	// const preLogin = () => {
	// 	let code = getCookie("code") ? getCookie("code") : "";
	// 	login({ code: code, pid: Number(pid) }).then((res) => {

	// 	});
	// }
	// preLogin();
	const handleBack = () => {
		if (backUrl === "/orderlist" || backUrl === "/buyrecord") {
			router.back();
		} else {
			router.push("/businesspush");
		}
	};
	const jdFn = (num : number) => {
		if (num) {
			return (num / 4) * 100;
		} else {
			return 0;
		}
	};
	const sj = async () => {
		let { data } = await userInfoApi({
			uid: getCookie("token") ? Number(getCookie("token")) : "",
		});
		if (data?.price < detailInfo.value.price) {
			rechargeShow.value = true;
		} else {
			if (!data.phone) {
				bindPhoeShoe.value = true;
				return;
			}
			let loading = showLoadingToast({
				duration: 0,
				message: "加载中...",
				forbidClick: true,
			});
			let { code, msg } = await procurebuyApi({
				uid: getCookie("token") ? Number(getCookie("token")) : "",
				procuresid: Number(id),
				state: 1,
			});
			loading.close();
			if (code === 0) {
				showSuccessToast("购买成功");
				getDetail();
			} else {
				showToast(msg);
			}
		}
	};
	const handlePhone = () => {
		if (detailInfo.value.buy === 2) {
			let phoneNumber = detailInfo?.value?.phone || "";
			showConfirmDialog({
				title: "",
				message: "联系客户请说公司客服给的联系方式，不要说平台购买的！",
			}).then(() => {
				var callLink = "tel:" + phoneNumber;
				var link = document.createElement("a");
				link.setAttribute("href", callLink);
				link.setAttribute("style", "visibility:hidden");
				document.body.appendChild(link);
				link.click();
				return;
			}).catch(() => {
				// on cancel
			});

		}
	};
	const handleSj = () => {
		showConfirmDialog({
			title: "提示",
			message: "确认操作？",
		})
			.then(() => {
				sj();
			})
			.catch(() => {
				// on cancel
			});
	};
	const handleCloseRecharge = async () => {
		rechargeShow.value = false;
	};

	const dz = async () => {
		let { data } = await userInfoApi({
			uid: getCookie("token") ? Number(getCookie("token")) : "",
		});
		if (data?.price < detailInfo.value.price) {
			rechargeShow.value = true;
		} else {
			if (!data.phone) {
				bindPhoeShoe.value = true;
				return;
			}
			let loading = showLoadingToast({
				message: "加载中...",
				forbidClick: true,
			});
			let { code, msg } = await procurebuyApi({
				uid: getCookie("token") ? Number(getCookie("token")) : "",
				procuresid: Number(id),
				state: 2,
			});
			loading.close();
			if (code === 0) {
				showSuccessToast("购买成功");
				getDetail();
			} else {
				showToast(msg);
			}
		}
	};
	const handleDz = () => {
		showConfirmDialog({
			title: "提示",
			message: "确认操作？",
		})
			.then(() => {
				dz();
			})
			.catch(() => {
				// on cancel
			});
	};
	const handlePhoneCancel = () => {
		bindPhoeShoe.value = false;
	};
	const handleBindPhoneConfirm = async (phone : string) => {
		bindPhoeShoe.value = false;
		let loading = showLoadingToast({
			duration: 0,
			message: "请稍后...",
			forbidClick: true,
		});
		let { code, msg } = await userphoneApi({
			uid: getCookie("token") ? Number(getCookie("token")) : "",
			phone,
		});
		if (code === 0) {
			loading.close();
			handleDz();
		} else {
			showToast({
				message: msg,
				position: "top",
			});
		}
	};

	const goDetails = (data : any) => {
		console.log('datadata', data.id)
		// /detail/:id
		router.push({ name: 'Detail', params: { id: data.id} });
	}
</script>
<style lang="scss" scoped>
	@import "./index.scss";

	.blueSpan {
		color: blue;
	}

	.moreBussiness-title {
		font-size: 16px;
		padding: 10px;
		color: #000;
		margin-top: 10px;
	}

	.moreBussiness-item {
		background: #fff;
		margin: 10px;
		padding: 10px;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
	}

	.moreBussiness-item>span:first-child {
		display: inline-block;
		white-space: nowrap;
		text-overflow: ellipsis;
		color: #d43030;
		font-weight: bold;
		font-size: 15px;
	}

	.moreBussiness-item>span:nth-child(2) {
		font-size: 14px;
		margin: 10px 0;
	}

	.moreBussiness-item-foot {
		display: flex;
		justify-content: space-between;
		margin-top: 10px;
	}

	.moreBussiness-item-foot>span:first-child {
		color: #999999;
		font-size: 12px;
	}

	.moreBussiness-item-foot>span:nth-child(2) {
		color: #000000;
		font-size: 12px;
		font-weight: bold;
	}
</style>